package net.libra.ui.tip
{
	import net.libra.ui.layer.LayerDef;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import net.libra.ui.base.BaseSprite;
	import net.libra.ui.layer.LayerManager;
	
	public class BaseTip extends BaseSprite implements ITip
	{
		static protected var tips:Array = [];
		
		static protected function allmove(event:MouseEvent):void
		{
			var x:int = int(event.stageX);
			var y:int = int(event.stageY);
			
			for(var i:uint=0;i<tips.length;i++)
			{
				ITip(tips[i]).move(x,y);
			}
			event.updateAfterEvent();
		}
		static protected function addTip(tip:ITip):void
		{
			if(tips.indexOf(tip) != -1)
			{
				return;
			}
			tips.push(tip);
			LayerManager.getStage().addEventListener(MouseEvent.MOUSE_MOVE,allmove);
			tip.move(LayerManager.getStage().mouseX,LayerManager.getStage().mouseY);
		}
		static protected function removeTip(tip:ITip):void
		{
			if(tips.indexOf(tip) == -1)
			{
				return;
			}
			tips.splice(tips.indexOf(tip),1);
			
			if(tips.length < 1)
			{
				LayerManager.getStage().removeEventListener(MouseEvent.MOUSE_MOVE,allmove);
			}
		}
		
		
		public function BaseTip()
		{
			super();
		}
		
		public function show(layer:String=null):void
		{
			if(isNeedUpdate)
			{
				updateNow();
			}
			addTip(this);
			LayerManager.addChild(display,layer||LayerDef.TIP);
		}
		
		public function hide():void
		{
			LayerManager.removeChild(display);
			removeTip(this);
		}
		
		public function move(x:int, y:int):void
		{
			x += 15;
			y += 20;
			if(x + width > LayerManager.getWidth() - 5)
			{
				//x -= (width + 5 + 15);
				x = LayerManager.getWidth() - 5 - width;
			}
			
			if(y + height > LayerManager.getHeight() - 5)
			{
				//y = LayerManager.getHeight() - 5 - height;
				y -= 20;
				y -= height;
			}
			
			display.x = x;
			display.y = y;
		}
		
		public function get display():DisplayObject
		{
			return this;
		}
		
		override public function get width():Number
		{
			return display.width;
		}
		override public function get height():Number
		{
			return display.height;
		}
	}
}